package com.control.qct.businesssteward.base;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;


import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.httputils.NetProtocol;
import com.control.qct.businesssteward.service.ForceOfflineReceiver;
import com.control.qct.businesssteward.utils.ActivityCollector;
import com.control.qct.businesssteward.utils.SPUtils;
import com.control.qct.businesssteward.utils.ToastUtils;
import com.jaeger.library.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by Administrator on 2017/5/15 0015.
 */

public abstract class BaseActivity extends AppCompatActivity {
    protected Toolbar toolbar;
    protected TextView tv_left, tv_title, tv_right;
    protected BaseActivity context;
    private int resId;
    public List<Fragment> fragments;
    private Unbinder unbinder;
    protected NetProtocol mNetProtocol;//请求网络集合类
    protected SPUtils mSPUtils;
    private ForceOfflineReceiver mReceiver;

    public BaseActivity(int resId) {
        this.resId = resId;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(resId);
        Bundle extras = getIntent().getExtras();
        fragments = new ArrayList<>();
        if (null != extras) {
            getBundleExtras(extras);
        }
        context = this;
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_left = (TextView) findViewById(R.id.tv_toolbar_back);
        tv_title = (TextView) findViewById(R.id.tv_toolbar_title);
        tv_right = (TextView) findViewById(R.id.tv_toolbar_right);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        setStatusBar(Color.parseColor("#05C1AB"));//设置状态栏颜色
        initContentView(savedInstanceState);
        unbinder = ButterKnife.bind(this); //绑定注解
        mNetProtocol = NetProtocol.getInstance(this);
        mSPUtils = SPUtils.getInstance(this);
        ActivityCollector.addActivity(this);
        initView();
    }

    /**
     * Bundle  传递数据
     *
     * @param extras
     */
    protected void getBundleExtras(Bundle extras) {
    }

    ;

    protected void initContentView(Bundle bundle) {
    }

    ;//恢复数据

    protected abstract void initView();//初始化控件

    /**
     * 改变状态栏颜色
     *
     * @param colorId
     */
    public void setStatusBar(int colorId) {
        if (colorId != Color.BLUE) {
            StatusBarUtil.setColorNoTranslucent(this, colorId);
        } else {
            StatusBarUtil.setColorNoTranslucent(this, Color.BLUE);
        }
    }

    /**
     * 设置标题栏返回键
     *
     * @param listener
     */
    public void setLeftIcon(View.OnClickListener listener) {
        setLeftIcon(R.drawable.icon_arrow_left, "", listener);
    }

    /**
     * 设置标题栏返回键
     *
     * @param resId
     * @param msg
     * @param listener
     */
    public void setLeftIcon(int resId, String msg, View.OnClickListener listener) {
        tv_left.setVisibility(View.VISIBLE);
        if (msg != null) {
            tv_left.setText(msg);
        }
        if (resId != 0) {
            Drawable drawable = ContextCompat.getDrawable(this, resId);
            // 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_left.setCompoundDrawables(drawable, null, null, null);
        }
        if (listener != null) {
            tv_left.setOnClickListener(listener);
        }
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        if (title != null) {
            tv_title.setVisibility(View.VISIBLE);
            tv_title.setText(title);
        }
    }

    /**
     * 设置标题栏右控件
     *
     * @param msg
     */
    public void setRightIcon(String msg) {
        setRightIcon(0, msg, null);
    }

    /**
     * 设置标题栏右控件
     *
     * @param msg
     * @param listener
     */
    public void setRightIcon(String msg, View.OnClickListener listener) {
        setRightIcon(0, msg, listener);
    }


    /**
     * 设置标题栏右控件
     *
     * @param resId
     * @param msg
     * @param listener
     */
    public void setRightIcon(int resId, String msg, View.OnClickListener listener) {
        tv_right.setVisibility(View.VISIBLE);
        if (resId != 0) {
            Drawable drawable = ContextCompat.getDrawable(this, resId);
            // 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_right.setCompoundDrawables(drawable, null, null, null);
        }
        if (msg != null) {
            tv_right.setText(msg);
        }
        if (listener != null) {
            tv_right.setOnClickListener(listener);
        }
    }

    /**
     * Toast显示
     */
    protected void showShortToast(String string) {
        ToastUtils.showShortToast(this, string);
    }

    protected void showShortToast(int stringId) {
        ToastUtils.showShortToast(this, stringId);
    }

    protected void showLongToast(String string) {
        ToastUtils.showShortToast(this, string);
    }

    protected void showLongToast(int stringId) {
        ToastUtils.showShortToast(this, stringId);
    }

    /**
     * 界面跳转
     *
     * @param cls 目标Activity
     */
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 跳转界面，传参
     *
     * @param cls    目标Activity
     * @param bundle 数据
     */
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (null != bundle)
            intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 跳转界面并关闭当前界面
     *
     * @param cls 目标Activity
     */
    public void startActivityAndFinish(Class<?> cls) {
        startActivityAndFinish(cls, null);
    }

    /**
     * @param cls    目标Activity
     * @param bundle 数据
     */
    public void startActivityAndFinish(Class<?> cls, Bundle bundle) {
        startActivity(cls, bundle);
        finish();
    }

    /**
     * startActivityForResult
     *
     * @param cls         目标Activity
     * @param requestCode 发送判断值
     */
    public void startActivityForResult(Class<?> cls, int requestCode) {
        Intent intent = new Intent(this, cls);
        startActivityForResult(intent, requestCode);
    }

    /**
     * startActivityForResult with bundle
     *
     * @param cls         目标Activity
     * @param requestCode 发送判断值
     * @param bundle      数据
     */
    public void startActivityForResult(Class<?> cls, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, cls);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 替换fragment页面
     *
     * @param fragment
     */
    public void replaceFragment(int resId, Fragment fragment) {
        replaceFragment(resId, fragment, false);
    }

    /**
     * 替换fragment页面
     *
     * @param fragment
     */
    public void replaceFragment(int resId, Fragment fragment, boolean isBack) {
        FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
        beginTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        beginTransaction.replace(resId, fragment);
        if (isBack) {
            beginTransaction.addToBackStack(null);
        }
        beginTransaction.commit();
    }


    /**
     * 添加fragment，存在则显示，不存在则添加，并隐藏前一个fragment
     *
     * @param resId
     * @param f
     */
    public void addFragment(int resId, Fragment f) {
        addFragment(resId, f, false);
    }

    /**
     * 添加fragment，存在则显示，不存在则添加，并隐藏前一个fragment
     *
     * @param resId
     * @param f
     */
    public void addFragment(int resId, Fragment f, boolean isBack) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
        if (fragments != null && fragments.size() > 0) { //遍历集合，隐藏所有fragment
            for (Fragment fragment : fragments) {
                beginTransaction.hide(fragment);
            }
        }
        if (!f.isAdded()) {//fragment是否存在，存在则显示，不存在则添加
            beginTransaction.add(resId, f);
        } else {
            beginTransaction.show(f);
        }
        fragments.add(f);
        if (isBack) {
            beginTransaction.addToBackStack(null);
        }
        beginTransaction.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.control.qct.business_steward.FORCE_OFFLINE");
        mReceiver = new ForceOfflineReceiver();
        registerReceiver(mReceiver,intentFilter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mReceiver != null){
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
        if (unbinder != null) { //解绑注解
            unbinder.unbind();
            unbinder = null;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {//判断是否是EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
